<?php

class Simi extends API_Controller {

    private $register = 'http://www.simsimi.com/func/register';
    private $update = 'http://www.simsimi.com/func/update';
    private $chat = 'http://www.simsimi.com/func/reqN';
    private $uid;
    private $filename;
    private $path;

    public function __construct() {
        parent::__construct();
        $this->load->library('Curl');
        $this->path = dirname(dirname(dirname(__FILE__)));
    }

    private function register() {
        $this->filename = md5(time());
        $this->curl->setpathcookie($this->path . '/cache/' . $this->filename . '.txt');
        $json = $this->curl->get($this->register);
        $result = json_decode($json, TRUE);
        $this->uid = $result['uid'];
    }

    private function update($lang) {
        $this->curl->setcookie('simsimi_uid=' . $this->uid);
        $this->curl->setpathcookie($this->path . '/cache/' . $this->filename . '.txt');
        $url = $this->update . '/?uid=' . $this->uid . '&lc=' . $lang;
        $json = $this->curl->get($url);
    }

    public function chat() {
        $req = $this->input->get('req');
        $lang = $this->input->get('lang');

        $lang = empty($lang) == TRUE ? 'vn' : $lang;

        if (empty($req) == TRUE) {
            $this->response('INVALID_PARAMS');
        }

        $this->register();
        $this->update($lang);

        $this->curl->setcookie('simsimi_uid=' . $this->uid);
        $url = $this->chat . '?lc=' . $lang . '&req=' . urlencode($req) . '&ft=0.0&fl=http%3A%2F%2Fwww.simsimi.com%2Ftalk.htm';

        $json = $this->curl->get($url);
        $result = json_decode($json, TRUE);

        $response['message'] = $result['sentence_resp'];
        $response['emotion'] = $result['emotion'];

        $this->response('GET_SUCCESS', $response);
    }

}
